package com.song.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 判断字符是否乱码
 * @author liuxin
 *
 */
public class CheckMessyCode {

    public static boolean checkMessyCode(String str) {
        return new CheckMessyCode().isMessyCode(str);
    }

    /**
     * 判断字符串是否为乱码
     *
     * @param strName
     *            传入需要判断的字符串
     * @return 如果为乱码则返回true，否则返回false
     */
    public boolean isMessyCode(String strName) {
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
        Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = 0;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)) {
                if (!this.isChinese(c)) {
                    count = count + 1;
//					System.err.println("乱码字符：" + c);
                }
                chLength++;
            }
        }
        try {
            return count / chLength > 0.4;
        }catch (Exception e) {
            return false;
        }
    }

    private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || c == '='
                || c == '+'
                || c == '<'
                || c == '>') {
            return true;
        }

        return false;
    }

}
